//
//  CourseDownloadViewController.m
//  网易公开课项目
//
//  Created by 林 艺 on 13-11-18.
//  Copyright (c) 2013年 Marklin. All rights reserved.
//

#import "CourseDownloadViewController.h"
#import "CourseVideoModel.h"
#import "DownloaderHelper.h"
#import "LoadCourseDataManager.h"

@interface CourseDownloadViewController ()

@end

@implementation CourseDownloadViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"选择视频";
        self.translatedArray = [[NSMutableArray alloc] init];
        self.untranslatedArray = [[NSMutableArray alloc] init];
        _downloadSelectedArray = [[NSMutableArray alloc] init];

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    if (_downloadSelectedArray.count == 0)
    {
        _downloadStartButton.enabled = NO;
    }
    [self postButtonView];
    [self _initNavigationBarItem];    
}

- (void)_initNavigationBarItem
{
    //取消
    UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
    [back setBackgroundImage:[UIImage imageNamed:@"btn_right.png"] forState:UIControlStateNormal];
    
    [back setTitle:@"取消" forState:UIControlStateNormal];
    back.titleLabel.font = [UIFont systemFontOfSize:11];
    [back addTarget:self action:@selector(cancelClicked) forControlEvents:UIControlEventTouchUpInside];
    back.frame = CGRectMake(0, 0, 50, 34);
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithCustomView:back];
    self.navigationItem.rightBarButtonItem = rightButton;

}

- (void)cancelClicked
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark --
#pragma 归档
- (NSString *)getDownloadPath
{
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    
    return [path stringByAppendingPathComponent:@"download.archiver"];
}

- (void)DownloadRecordWithModel
{
    //先读取本地文件
    NSData *readDatas = [NSData dataWithContentsOfFile:[self getDownloadPath]];
    if (readDatas == nil)
    {
        NSMutableArray *dataModels = [[NSMutableArray alloc] init];
        [dataModels addObject:self.courseModel];
        NSMutableData *datas = [NSMutableData data];
        NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:datas];
        [archiver encodeObject:dataModels forKey:@"kDownloadDatas"];
        [archiver finishEncoding];
        [datas writeToFile:[self getDownloadPath] atomically:YES];
    }
    else
    {
        NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:readDatas];
        NSMutableArray *readModels = [unArchiver decodeObjectForKey:@"kDownloadDatas"];
        //判断是否已有记录
        BOOL isHvaeSelectedToDownload = NO;
        NSInteger index;
        for (int i = 0; i < readModels.count; i++)
        {
            CourseModel *model = readModels[i];
            if ([model.title isEqualToString:self.courseModel.title])
            {
                isHvaeSelectedToDownload = YES;
                index = i;
                break;
            }
            
        }
        
        //如果有记录
        if (isHvaeSelectedToDownload)
        {
            for (CourseVideoModel *videoModel in self.courseModel.videoList)
            {
                for (CourseVideoModel *downModel in _downloadSelectedArray)
                {
                    if ([videoModel.pnumber isEqualToNumber:downModel.pnumber])
                    {
                        if (downModel.isSelectedToDownload == YES)
                        {
                            videoModel.isDownloaded = YES;
                        }
                    }//if ([videoModel.pnumber isEqualToNumber:downModel.pnumber])
                }
            }
            NSMutableData *datas = [NSMutableData data];
            NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:datas];
            [archiver encodeObject:readModels forKey:@"kDownloadDatas"];
            [archiver finishEncoding];
            [datas writeToFile:[self getDownloadPath] atomically:YES];
        }
        else//如果没有记录
        {
            [readModels addObject:self.courseModel];
            NSMutableData *datas = [NSMutableData data];
            NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:datas];
            [archiver encodeObject:readModels forKey:@"kDownloadDatas"];
            [archiver finishEncoding];
            [datas writeToFile:[self getDownloadPath] atomically:YES];
        }
        
    }//else ---> if (readDatas == nil)
    
}


#pragma mark --
#pragma mark buttonList
- (void)postButtonView
{
    UILabel *headLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 150, 20)];
    headLabel.font = [UIFont systemFontOfSize:15];
    headLabel.textColor = [UIColor brownColor];
    headLabel.backgroundColor = [UIColor clearColor];
    headLabel.text = @"已翻译";
    [self.scrollView addSubview:headLabel];

    _lessionHeight = 30+10;
    //添加翻译按钮
    for (int i = 0; i < _translatedArray.count; i++)
    {
        //中断循环标志位
        BOOL flag = NO;
        for (int j = 0; j < 3; j++)
        {
            int temp = i*3+j;
            
            CourseVideoModel *model = (CourseVideoModel *)[_translatedArray objectAtIndex:temp];
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button setBackgroundImage:[UIImage imageNamed:@"course_load_unselected.png"] forState:UIControlStateNormal];
            [button setBackgroundImage:[UIImage imageNamed:@"course_load_unselected_avtive.png"] forState:UIControlStateHighlighted];
//            [button setBackgroundImage:[UIImage imageNamed:@"course_load_unselected_avtive.png"] forState:UIControlStateDisabled];
            [button addTarget:self action:@selector(lessionTranslatedClicked:) forControlEvents:UIControlEventTouchUpInside];
            button.frame = CGRectMake(10+100*j, 40+(45+5)*i, 99, 45);
            button.tag = kLessionTranslatedTag+temp;
            if (model.isDownloaded || model.isDownloading || model.isSelectedToDownload)
            {
                [button setTitle:[NSString stringWithFormat:@"第%@课 已下", model.pnumber] forState:UIControlStateNormal];
                [button setBackgroundImage:[UIImage imageNamed:@"course_btn.png"] forState:UIControlStateNormal];
                button.enabled = NO;
            }
            else
            {
                [button setTitle:[NSString stringWithFormat:@"第%@课 ", model.pnumber] forState:UIControlStateNormal];
            }
            button.titleLabel.font = [UIFont systemFontOfSize:15];
            [self.scrollView addSubview:button];
            
            if (temp >= _translatedArray.count-1)
            {
                flag = YES;
                break;
            }
        }//for (int j = 0; j < 3; j++)
        _lessionHeight += 50;
        if (flag)
        {
            break;
        }
    }//for (int i = 0; i <= _translatedArray.count/3; i++)
    
    if (_untranslatedArray.count == 0)
    {
        UILabel *footLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, _lessionHeight+5, 150, 20)];
        footLabel.font = [UIFont systemFontOfSize:15];
        footLabel.textColor = [UIColor brownColor];
        footLabel.tag = 38;
        footLabel.backgroundColor = [UIColor clearColor];
        footLabel.text = @"全部翻译完成";
        [self.scrollView addSubview:footLabel];
        _lessionHeight += 35;
    }
    else
    {
        UILabel *footLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, _lessionHeight+5, 150, 20)];
        footLabel.font = [UIFont systemFontOfSize:15];
        footLabel.textColor = [UIColor brownColor];
        footLabel.tag = 38;
        footLabel.backgroundColor = [UIColor clearColor];
        footLabel.text = @"未翻译";
        [self.scrollView addSubview:footLabel];
        _lessionHeight += 35;
        CGFloat tempHeight = _lessionHeight;
        //添加未翻译按钮
        for (int i = 0; i < _untranslatedArray.count; i++)
        {
            //中断循环标志位
            BOOL flag = NO;
            for (int j = 0; j < 3; j++)
            {
                int temp = i*3+j;
                
                CourseVideoModel *model = (CourseVideoModel *)[_untranslatedArray objectAtIndex:temp];
                UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                [button setBackgroundImage:[UIImage imageNamed:@"course_load_unselected.png"] forState:UIControlStateNormal];
                [button setBackgroundImage:[UIImage imageNamed:@"course_load_unselected_avtive.png"] forState:UIControlStateHighlighted];
                [button addTarget:self action:@selector(lessionUntranslatedClicked:) forControlEvents:UIControlEventTouchUpInside];
                button.frame = CGRectMake(10+100*j, tempHeight+(45+5)*i, 99, 45);
                button.tag = kLessionUntranslatedTag+temp;
                [button setTitle:[NSString stringWithFormat:@"第%@课", model.pnumber] forState:UIControlStateNormal];
                [self.scrollView addSubview:button];
                
                if (temp >= _untranslatedArray.count-1)
                {
                    flag = YES;
                    break;
                }
            }//for (int j = 0; j < 3; j++)
            _lessionHeight += 50;
            if (flag)
            {
                break;
            }
        }//for (int i = 0; i < _translatedArray.count/3; i++)
    }
    
    self.scrollView.contentSize = CGSizeMake(320, _lessionHeight);
    
}

- (void)lessionTranslatedClicked:(UIButton *)button
{
    CourseVideoModel *model = (CourseVideoModel *)[_translatedArray objectAtIndex:button.tag-kLessionTranslatedTag];
    if (model.isSelectedToDownload)
    {
        [button setBackgroundImage:[UIImage imageNamed:@"course_load_unselected.png"] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:@"course_load_unselected_avtive.png"] forState:UIControlStateHighlighted];
        model.isSelectedToDownload = NO;
        [self downloadArrayRemoveMemberWithModel:model];
        _selectedCapacity -= [model.mp4size integerValue];
        self.selectedCapacityLabel.text = [NSString stringWithFormat:@"已选:%0.2fMB 可用空间:43.51GB", _selectedCapacity/1024.0/1024.0];
        if (_downloadSelectedArray.count == 0)
        {
            _downloadStartButton.enabled = NO;
        }
    }
    else
    {
        [button setBackgroundImage:[UIImage imageNamed:@"course_load_selected.png"] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:@"course_load_selected_avtive.png"] forState:UIControlStateHighlighted];
        model.isSelectedToDownload = YES;
        [self downloadArrayAddMemberWithModel:model];
        _selectedCapacity += [model.mp4size integerValue];
        self.selectedCapacityLabel.text = [NSString stringWithFormat:@"已选:%0.2fMB 可用空间:43.51GB", _selectedCapacity/1024.0/1024.0];

    }
    
}

- (void)lessionUntranslatedClicked:(UIButton *)button
{
    CourseVideoModel *model = (CourseVideoModel *)[_untranslatedArray objectAtIndex:button.tag-kLessionUntranslatedTag];
    if (model.isSelectedToDownload)
    {
        [button setBackgroundImage:[UIImage imageNamed:@"course_load_unselected.png"] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:@"course_load_unselected_avtive.png"] forState:UIControlStateHighlighted];
        model.isSelectedToDownload = NO;
        [self downloadArrayRemoveMemberWithModel:model];
        _selectedCapacity -= [model.mp4size integerValue];
        self.selectedCapacityLabel.text = [NSString stringWithFormat:@"已选:%0.2fMB 可用空间:43.51GB", _selectedCapacity/1024.0/1024.0];
        if (_downloadSelectedArray.count == 0)
        {
            _downloadStartButton.enabled = NO;
        }
    }
    else
    {
        [button setBackgroundImage:[UIImage imageNamed:@"course_load_selected.png"] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:@"course_load_selected_avtive.png"] forState:UIControlStateHighlighted];
        model.isSelectedToDownload = YES;
        [self downloadArrayAddMemberWithModel:model];
        _selectedCapacity += [model.mp4size integerValue];
        //判断选中课程容量大小
        self.selectedCapacityLabel.text = [NSString stringWithFormat:@"已选:%0.2fMB 可用空间:43.51GB", _selectedCapacity/1024.0/1024.0];
    }

}

- (void)downloadArrayRemoveMemberWithModel:(CourseVideoModel *)model
{
    NSInteger index = 0;
    for (int i = 0; i < _downloadSelectedArray.count; i++)
    {
        CourseVideoModel *compareModel = [_downloadSelectedArray objectAtIndex:i];
        if ([compareModel.title isEqualToString:model.title])
        {
            index = i;
            break;
        }
    }
    [_downloadSelectedArray removeObjectAtIndex:index];
    
    
}

- (void)downloadArrayAddMemberWithModel:(CourseVideoModel *)model
{
    [_downloadSelectedArray addObject:model];
    if (_downloadSelectedArray != nil)
    {
        _downloadStartButton.enabled = YES;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)downloadStartClicked:(UIButton *)sender
{
    DownloaderHelper *downloadHelper = [DownloaderHelper shareInstance];
    LoadCourseDataManager *dataManager = [LoadCourseDataManager shareInstance];
    
    for (CourseVideoModel *tempModel in _downloadSelectedArray)
    {
        for (CourseVideoModel *videoModel in self.courseModel.videoList)
        {
            if ([tempModel.pnumber isEqualToNumber:videoModel.pnumber])
            {
                videoModel.isSelectedToDownload = YES;
                
                NSLog(@"%d", self.courseModel.indentify);
                NSLog(@"%@", videoModel.pnumber);
                
                [downloadHelper startDownload:videoModel.repovideourlmp4 withKey:[NSString stringWithFormat:@"%d%@", self.courseModel.indentify, videoModel.pnumber]];
                NSString *temp = [NSString stringWithFormat:@"%d%@", self.courseModel.indentify, videoModel.pnumber];
                NSLog(@"<<<<<<<<<%@", temp);
                NSLog(@">>>>>>>>>%d", [temp integerValue]);
                break;
            }
        }
    }//for (CourseVideoModel *tempModel in _downloadSelectedArray)
    
    [dataManager writeToDownloadArchiverWithModel:self.courseModel];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kDownloadNotification object:self.courseModel];
    [self dismissViewControllerAnimated:YES completion:nil];

}
@end
